<template>
  <div class="purchase-paln-wrap table-gl-w">
    <a-tabs @change="changeStatus" size="mini">
      <a-tab-pane v-for="tab in tabsList" :key="tab.key">
        <template #title>
          <span>{{ tab.title }}</span>
          <span v-if="tab.key">({{ countMap[tab.key] || 0 }})</span>
        </template>
      </a-tab-pane>
    </a-tabs>
    <div class="search-w table-filter-form">
      <FilterTable :filterItem="filterItem" :isReset="true" :maxNum="3" @search="searchByVal" />
    </div>
    <div class="table-gl-con">
      <TableWrap style="flex: 1" @refresh="getTableList">
        <template #headerLeft>
          <a-space>
            <a-button type="primary" size="medium" @click="openAddPurchasePaln" v-if="!searchVal.status && $authPass('procurement.purchase.plan.save')">添加采购计划</a-button>
            <template v-else>
              <a-button type="primary" size="medium" @click="submitAudit(selectIds)" v-if="searchVal.status == 1 && $authPass('procurement.purchase.plan.submit')">提交审核</a-button>
              <a-button type="primary" size="medium" @click="openAuditDialog(selectIds)" v-if="searchVal.status == 10 && $authPass('procurement.purchase.plan.audit')">审核</a-button>
              <a-button class="gray-outline" size="medium" @click="submitCancellation(selectIds)" v-if="searchVal.status == 1 && $authPass('procurement.purchase.plan.cancel')">作废</a-button>
              <a-button class="gray-outline" size="medium" @click="submitRevocation(selectIds)" v-if="(searchVal.status == 10 || searchVal.status == 20) && $authPass('procurement.purchase.plan.revoke')">撤回草稿</a-button>
            </template>
          </a-space>
        </template>
        <template #tableBody>
          <a-table class="table-singe-line" ref="tableListref" :span-method="spanMethodAll" row-key="id" :expandable="expandable" :default-expand-all-rows="true" :loading="tableLoading" @selection-change="selectColumn" :row-selection="rowSelection" :columns="tableColumns" :data="tableList" size="mini" :pagination="false" :scroll="{ x: '100%', y: '100%' }">
            <template #columns>
              <a-table-column v-for="(item, index) of tableColumns" :fixed="item.fixed" :key="index" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
                <template v-if="item.dataIndex == 'sort'" #cell="{ rowIndex }">
                  <p>{{ rowIndex + 1 }}</p>
                </template>
                <template v-else-if="item.dataIndex == 'shop'" #cell="{ record }">
                  <div class="flex-c-sb" style="padding-right: 20px">
                    <div class="order-w flex">
                      <div class="order-detail-item" style="width: 160px">
                        <div class="flex-c">
                          <span class="label">计划单号：</span>
                          <span class="highlight cursor" @click="toDetail(record)">{{ record.billNo }}</span>
                          <CopyText class="popup-edit-icon-hover" style="margin-left: 5px" :val="record.billNo" />
                        </div>
                        <!-- <p>
                          <span class="label">目的仓库：</span>
                          <span class="highlight">{{ record.warehouseName }}({{ record.warehouseCode }})</span>
                        </p> -->
                      </div>
                      <div class="order-detail-item" style="width: 120px">
                        <!-- <p><span class="label">产品种类：</span>{{ record.skuType }}</p> -->
                        <p><span class="label">计划数量：</span>{{ record.planAmt }}</p>
                      </div>
                      <div class="order-detail-item" style="width: 120px">
                        <p><span class="label">创建人：</span>{{ record.createUname }}</p>
                      </div>
                      <div class="order-detail-item" style="width: 200px">
                        <p><span class="label">创建时间：</span>{{ $setTime(record.gmtCreate, 'YYYY/MM/DD HH:mm') }}</p>
                      </div>
                      <!-- <div class="order-detail-item" style="width: 200px">
                        <p><span class="label">审核人：</span>{{ record.auditUname }}</p>
                        <p><span class="label">审核时间：</span>{{ $setTime(record.gmtAudit, 'YYYY/MM/DD HH:mm') }}</p>
                      </div>
                      <div class="order-detail-item" style="width: 140px">
                        <p><span class="label">产品种类：</span>{{ record.skuType }}</p>
                        <p><span class="label">计划数量：</span>{{ record.planAmt }}</p>
                      </div>
                      <div class="order-detail-item" style="width: 140px">
                        <p><span class="label">采购数量：</span>{{ record.purchaseRealAmt }}</p>
                        <p><span class="label">已入库数：</span>{{ record.warehouseRealAmt }}</p>
                      </div> -->
                      <div class="order-detail-item" style="width: 150px">
                        <TextLimit :val="'备注：' + record.remark" :rows="1" />
                      </div>
                      <div class="order-detail-item" style="width: 150px">
                        <TextLimit v-if="record.auditRemark" class="warningColor" :val="'驳回原因：' + record.auditRemark" :rows="1" />
                      </div>
                      <!-- <div class="order-detail-item" style="width: 150px">
                        <div class="flex">
                          <span class="label" style="flex-shrink: 0">附件：</span>
                          <a-popover v-if="record.attachment">
                            <p class="text-limit">{{ record.attachment }}</p>
                            <template #content>
                              <p v-for="link in record.attachment.split(',')" :key="link">{{ link }}</p>
                            </template>
                          </a-popover>
                          <p v-else>--</p>
                        </div>
                      </div> -->
                    </div>
                    <div class="flex-c">
                      <a-space>
                        <a-tag color="arcoblue" size="small" bordered>{{ statusMap[record.status] }}</a-tag>
                        <div style="width: 60px; text-align: right">
                          <a-button type="text" size="mini" @click="openEditDialog(record)" v-if="record.status == 1 && $authPass('procurement.purchase.plan.edit')">编辑</a-button>
                          <a-button type="text" size="mini" @click="openAuditDialog([record.id])" v-if="record.status == 10 && $authPass('procurement.purchase.plan.audit')">审核</a-button>
                          <a-button type="text" size="mini" @click="submitRevocation([record.id])" v-if="record.status == 20 && $authPass('procurement.purchase.plan.revoke')">撤回草稿</a-button>
                          <a-button type="text" @click="toDetail(record)" size="mini" v-if="[0, 30, 40].includes(record.status)">详情</a-button>
                        </div>
                        <a-dropdown>
                          <icon-more class="table-btn-more" />
                          <template #content>
                            <a-doption @click.stop="submitAudit([record.id])" v-if="record.status == 1 && $authPass('procurement.purchase.plan.submit')">提交审核</a-doption>
                            <a-doption @click.stop="submitCancellation([record.id])" v-if="record.status == 1 && $authPass('procurement.purchase.plan.cancel')">作废</a-doption>
                            <a-doption @click.stop="submitRevocation([record.id])" v-if="record.status == 10 && $authPass('procurement.purchase.plan.revoke')">撤回草稿</a-doption>
                            <a-doption @click.stop="toDetail(record)" v-if="![0, 30, 40].includes(record.status)">详情</a-doption>
                            <a-doption @click.stop="openLogList(record)">日志</a-doption>
                          </template>
                        </a-dropdown>
                      </a-space>
                    </div>
                  </div>
                </template>
              </a-table-column>
            </template>
            <template #expand-row="{ record }">
              <a-table class="table-singe-line show-border-table" row-class="child-row" :show-header="false" row-key="id" :bordered="false" :columns="tableColumns" :data="record.billItems" size="mini" :pagination="false">
                <template #columns>
                  <a-table-column :width="10" />
                  <a-table-column :width="40" />
                  <a-table-column v-for="(item, index) of tableColumns" :key="index" :fixed="item.fixed" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
                    <template v-if="item.dataIndex == 'sort'" #cell> </template>
                    <template v-else-if="item.dataIndex == 'shop'" #cell="option">
                      <p style="color: #ccc">{{ $extract(marketPlaceList[option.record.marketplaceId], 'name') || '--' }}</p>
                      <TextLimit :rows="1" :val="option.record.shopName" />
                    </template>
                    <template v-else-if="item.dataIndex == 'img'" #cell="option">
                      <ImgPopover :src="option.record.productImg">
                        <template #con>
                          <a-image width="40" height="40" fit="contain" :src="option.record.productImg" />
                        </template>
                      </ImgPopover>
                    </template>
                    <template v-else-if="item.dataIndex == 'name'" #cell="option">
                      <TextLimit :rows="1" :val="option.record.productName" />
                    </template>
                    <template v-else-if="item.dataIndex == 'sku'" #cell="option">
                      <ShowSpuDetailBySku :val="option.record.sku" :showLimit="true" :rows="1" />
                      <p>{{ option.record.cateName || '--' }}</p>
                    </template>
                    <template v-else-if="item.dataIndex == 'msku'" #cell="option">
                      <TextLimit :rows="1" :val="option.record.msku || '--'" />
                      <TextLimit :rows="1" :val="option.record.asin || '--'" />
                    </template>
                    <template v-else-if="item.dataIndex == 'productSpecs'" #cell="option">
                      <TextLimit :val="getProductSpecs(option.record)" />
                    </template>
                    <template v-else-if="item.dataIndex == 'urgent'" #cell="option">
                      <p>{{ option.record.urgent ? '加急' : '否' }}</p>
                    </template>
                    <template v-else-if="item.dataIndex == 'gmtPlanDelivery'" #cell="option">
                      <p>{{ $setTime(option.record.gmtPlanDelivery, 'YYYY/MM/DD') }}</p>
                    </template>

                    <template v-else-if="item.dataIndex == 'associationNo'" #cell="option">
                      <p class="highlight">{{ option.record.purchaseNo }}</p>
                    </template>
                  </a-table-column>
                </template>
              </a-table>
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :total="total" :default-page-size="searchVal.pageSize" :current="searchVal.pageNum" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>
  <!-- 编辑采购计划 -->
  <EditPurchsePlan v-if="showEditDialog" :isShow="showEditDialog" :currentData="currentData" @closed="showEditDialog = false" @success="getTableList" />
  <!-- 审核 -->
  <Audit v-if="showAuditDialog" :isShow="showAuditDialog" @closed="showAuditDialog = false" @success="audit" />
  <!-- 日志列表 -->
  <CommonLogsDialog v-if="showLogDialog" api="findPurchasePlanLogPage" :id="currentData.id" :isShow="showLogDialog" @closed="showLogDialog = false" />
</template>

<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { FilterTableItem } from '@/types/components'
  import FilterTable from '@/components/TableFilter.vue'
  import EditPurchsePlan from './components/editPurchsePlan.vue'
  import CommonLogsDialog from '@/components/Log/logsDialog.vue'
  import Audit from './components/audit.vue'
  import { useRouter } from 'vue-router'
  import { Message, Modal } from '@arco-design/web-vue'
  import { findPurchasePlanPage, findPurchasePlanCountByStatus, commitPurchasePlan, cancelPurchasePlan, revokePurchasePlan, auditPurchasePlan } from '@/api/purchase'
  import { marketPlaceList } from '@/utils/globalData'
  import useBaseDataStore from '@/store/modules/base-data'
  import { parseJson } from '@/utils'

  onMounted(async () => {
    getShopList()
    getUserList()
    getWareHouseList()
    getListAndCount()
  })
  const tableColumns: Array<any> = [
    {
      title: '序号',
      dataIndex: 'sort',
      width: 40,
    },
    {
      title: '站点/店铺',
      dataIndex: 'shop',
      width: 100,
    },
    {
      title: '图片',
      dataIndex: 'img',
      width: 60,
    },
    {
      title: '产品名称',
      dataIndex: 'name',
      width: 100,
    },
    {
      title: 'SKU/品类',
      dataIndex: 'sku',
      width: 100,
    },
    {
      title: 'MSKU/ASIN',
      dataIndex: 'msku',
      width: 100,
    },
    {
      title: 'SKU规格',
      dataIndex: 'productSpecs',
      width: 100,
    },
    {
      title: '销售员',
      dataIndex: 'salesmanName',
      width: 70,
    },
    {
      title: '是否加急',
      dataIndex: 'urgent',
      width: 70,
    },
    {
      title: '计划交期',
      dataIndex: 'gmtPlanDelivery',
      width: 90,
    },
    {
      title: '计划数量',
      dataIndex: 'planAmt',
      width: 70,
    },
    {
      title: '采购数量',
      dataIndex: 'purchaseRealAmt',
      width: 70,
    },
    {
      title: '已入库数',
      dataIndex: 'warehouseRealAmt',
      width: 70,
    },
    {
      title: '采购订单号',
      dataIndex: 'associationNo',
      width: 140,
    },
    {
      title: '采购负责人',
      dataIndex: 'purchaseUname',
      width: 80,
    },
  ]
  const expandable = ref<any>({
    title: '',
    defaultExpandAllRows: true,
    expandedRowKeys: [],
    width: 10,
  })
  const tabsList = [
    { key: '', title: '全部' },
    { key: 1, title: '草稿' },
    { key: 10, title: '待审核' },
    { key: 20, title: '待采购' },
    { key: 30, title: '采购中' },
    { key: 40, title: '已完成' },
  ]
  const statusMap = {
    0: '已废弃',
    1: '草稿中',
    10: '待审核',
    20: '待采购',
    30: '采购中',
    40: '已完成',
  }
  const filterItem = ref<Array<FilterTableItem>>([
    {
      type: 'input_keyword',
      key: 'billNos',
      keyItems: [{ label: '计划单号', value: 'billNos' }],
      keyWidth: '110',
      value: ref(),
      placeholder: '请输入',
      label: '',
      width: 160,
      isMultiple: true,
    },
    {
      type: 'input_keyword',
      key: 'skus',
      keyItems: [
        { label: 'SKU', value: 'skus' },
        { label: '产品名称', value: 'productName' },
        { label: 'MSKU', value: 'mskus' },
        { label: 'ASIN', value: 'asins' },
      ],
      keyWidth: '100',
      value: ref(),
      placeholder: '请输入',
      label: '',
      width: 160,
      isMultiple: true,
    },
    {
      type: 'keyword_date_range',
      key: 'gmtCreate',
      keyItems: [
        { label: '创建日期', value: 'gmtCreate' },
        { label: '审核日期', value: 'gmtAudit' },
      ],
      keyWidth: '100',
      value: ref(),
      placeholder: '请输入',
      label: '创建时间',
      width: 240,
      attrs: {
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        timePickerProps: { defaultValue: ['00:00:00', '23:59:59'] },
      },
    },
    {
      key: 'shopIds',
      label: '店铺',
      value: ref(),
      type: 'select_multiple',
      width: 120,
      optionItems: [],
    },
    {
      key: 'warehouseCode',
      label: '目的仓库',
      value: ref(),
      type: 'select',
      width: 120,
      optionItems: [],
    },
    {
      key: 'createUid',
      label: '创建人',
      value: ref(),
      type: 'select',
      width: 100,
      optionItems: [],
    },
  ])
  const rowSelection = ref({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any
  let searchVal = ref<any>({
    pageSize: 20,
    pageNum: 1,
    status: '',
  })
  const tableLoading = ref(false)
  const tableList = ref<Array<any>>([])
  const total = ref(0)
  const selectIds = ref([])
  const router = useRouter()
  const currentData = ref<any>({})
  const currentIds = ref<Array<any>>([])
  const showEditDialog = ref(false)
  const showAuditDialog = ref(false)
  const showLogDialog = ref(false)
  const countMap = ref<any>({})
  const filterData = ref<any>({})
  const useBaseData = useBaseDataStore()
  const tableListref = ref()

  // 显示sku规格
  function getProductSpecs(item: any) {
    let productSpecs = item.productSpecs ? parseJson(item.productSpecs, []) : []
    return productSpecs.map((el: any) => el.valueCn)?.join('*') || '--'
  }
  // 获取仓库列表
  async function getWareHouseList() {
    await useBaseData.getWareHouseList()
    filterItem.value[4].optionItems = useBaseData.warehouseList.map((el: any) => {
      return {
        label: el.warehouseName,
        value: el.warehouseCode,
      }
    })
  }
  // 获取店铺
  async function getShopList() {
    await useBaseData.getShopListAndShare()
    filterItem.value[3].optionItems = useBaseData.shopListAndShare.map((el: any) => {
      return {
        label: el.shopName,
        value: el.sellerMarketId,
      }
    })
  }
  // 获取所有用户列表
  async function getUserList() {
    await useBaseData.getUserList()
    filterItem.value[5].optionItems = useBaseData.userList.map((el: any) => {
      return {
        label: el.userName,
        value: el.id,
      }
    })
  }
  // 通过条件查询列表
  function searchByVal(info: any) {
    searchVal.value.pageNum = 1
    filterData.value = JSON.parse(JSON.stringify(info)) || {}
    getTableList()
  }
  // 分页
  function changePage(val: number) {
    searchVal.value.pageNum = val
    getTableList()
  }
  function sizeChange(val: number) {
    searchVal.value.pageSize = val
    getTableList()
  }
  function selectColumn(val: any) {
    selectIds.value = val
  }
  // 切换状态
  function changeStatus(status: number | string) {
    searchVal.value.status = status
    searchVal.value.pageNum = 1
    getTableList()
  }
  // 查询列表和数量合计
  function getListAndCount() {
    getTableList()
    getCountList()
  }
  // 查询各状态下数量合计
  async function getCountList() {
    const res: any = await findPurchasePlanCountByStatus()
    let counts = res?.data || []
    countMap.value = {}
    counts.forEach((el: any) => {
      countMap.value[el.status] = el.totalCount
    })
  }
  // 获取商品列表
  async function getTableList() {
    tableList.value = []
    tableListref.value.selectAll(false)
    let params = {
      ...searchVal.value,
      ...filterData.value,
    }
    tableLoading.value = true
    const res: any = await findPurchasePlanPage(params)
    tableLoading.value = false
    tableList.value = res?.data?.records || []
    total.value = res?.data?.total || 0
    expandable.value.expandedRowKeys = tableList.value.map((el: any) => el.id)
  }
  // 合并单元格
  function spanMethodAll(option: any) {
    let { column } = option
    if (column.dataIndex === 'shop') {
      return { rowspan: 1, colspan: 14 }
    }
  }

  // 添加采购计划
  function openAddPurchasePaln() {
    window.localStorage.removeItem('addPurchasePalnIds')
    router.push('/purchase/purchaseManagement/addPurchasePlan?addModel=purchasePlan')
  }
  // 查看采购计划详情
  function toDetail(item: any) {
    router.push(`/purchase/purchaseManagement/purchasePlanDetail?id=${item.id}`)
  }
  // 提交审核
  function submitAudit(ids: Array<string>) {
    if (!ids.length) {
      Message.error('请选择采购计划')
      return
    }
    Modal.confirm({
      title: '提交审核',
      content: `请再次确认是否需要提交审核`,
      cancelText: '取消',
      okText: '确认',
      titleAlign: 'start',
      onOk: async () => {
        const res: any = await commitPurchasePlan({ ids: ids })
        if (res) {
          Message.success('提交审核成功')
          getListAndCount()
        }
      },
    })
  }
  // 作废
  function submitCancellation(ids: Array<string>) {
    if (!ids.length) {
      Message.error('请选择采购计划')
      return
    }
    Modal.confirm({
      title: '作废',
      content: `请再次确认是否需要作废选中的采购计划`,
      cancelText: '取消',
      okText: '确认',
      titleAlign: 'start',
      onOk: async () => {
        const res: any = await cancelPurchasePlan({ ids: ids })
        if (res) {
          Message.success('作废成功')
          getListAndCount()
        }
      },
    })
  }
  // 撤回草稿
  function submitRevocation(ids: Array<string>) {
    if (!ids.length) {
      Message.error('请选择采购计划')
      return
    }
    Modal.confirm({
      title: '撤回草稿',
      content: `请再次确认是否需要把选中的采购计划撤回到草稿箱`,
      cancelText: '取消',
      okText: '确认',
      titleAlign: 'start',
      onOk: async () => {
        const res: any = await revokePurchasePlan({ ids: ids })
        if (res) {
          Message.success('撤回草稿箱成功')
          getListAndCount()
        }
      },
    })
  }
  // 打开编辑采购计划
  function openEditDialog(row: any) {
    currentData.value = row
    showEditDialog.value = true
  }
  // 打开日志列表
  function openLogList(row: any) {
    currentData.value = row
    showLogDialog.value = true
  }
  // 打开审核弹窗
  function openAuditDialog(ids: any) {
    if (!ids.length) {
      Message.error('请选择采购计划')
      return
    }
    currentIds.value = ids
    showAuditDialog.value = true
  }
  // 开始审核
  async function audit(auditRes: any) {
    const res: any = await auditPurchasePlan({
      ids: currentIds.value,
      pass: auditRes.state,
      remark: auditRes.result,
    })
    if (res) {
      Message.success(auditRes.state ? '审核通过' : '已驳回')
      getListAndCount()
    }
  }
</script>
<style lang="less" scoped>
  :deep(.arco-table-td) {
    background-color: var(--color-fill-1);
    height: auto;
  }
  :deep(.arco-table-tr-expand) {
    .arco-table-cell {
      padding: 0;
    }
    .arco-table {
      margin: 0 !important;
      .arco-table-td {
        border-bottom: 1px solid var(--color-neutral-3);
        height: 48px;
      }
    }
    background-color: #fff !important;
  }
  :deep(.child-row) {
    .arco-table-cell {
      padding: 2px 8px;
    }
  }
  :deep(.arco-table-tr-expand .arco-table-td) {
    background-color: #fff !important;
    border-bottom: none;
  }
  :deep(.arco-table-tr-expand tr:hover .arco-table-td) {
    background-color: var(--color-fill-1) !important;
  }
  :deep(.arco-table-expand .arco-table-cell) {
    display: none;
  }
  :deep(.arco-tabs-nav-tab) {
    background-color: #fff;
  }
  .order-w {
    color: #666;
    flex: 1;
    .order-detail-item {
      width: 200px;
    }
  }
</style>
